#include "stdafx.h"
#include "RunProcess.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CProcessLaunch::CProcessLaunch() :
m_hProcess(NULL)
{
}

CProcessLaunch::~CProcessLaunch()
{
	Join();
}

BOOL CProcessLaunch::Exec(LPCTSTR pszCmdLine)
{
	ATLASSERT(m_hProcess == NULL);

	PROCESS_INFORMATION pi;
	STARTUPINFO si = {0};

	//Set up the start up info struct.
	si.cb = sizeof(STARTUPINFO);
	si.wShowWindow = SW_HIDE;
	si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;

	// Note that dwFlags must include STARTF_USESHOWWINDOW if we
	// use the wShowWindow flags. This also assumes that the
	// CreateProcess() call will use CREATE_NEW_CONSOLE.

	// Launch the child process.
	if (!::CreateProcess(NULL, (LPTSTR)pszCmdLine, NULL, NULL, TRUE, CREATE_NEW_CONSOLE,
		NULL, NULL, &si, &pi))
	{
		return FALSE;
	}

	m_hProcess = pi.hProcess;
	// Close any useless handles
	::CloseHandle(pi.hThread);
	return TRUE;
}

void CProcessLaunch::Join(DWORD dwWaitTime)
{
	if(m_hProcess != NULL)
	{
		WaitForSingleObject(m_hProcess, dwWaitTime);
		CloseHandle(m_hProcess);
		m_hProcess = NULL;
	}
}
